package com.mms.utils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * Created by dan3652@sina.com on 2016-11-28 16:03.
 */
public class SendEmailUtils {
    public static Properties properties ;
    public static MyAuthenticator authenticator;


    public static Properties getProperties() {
        return properties;
    }

    public static void setProperties(Properties properties) {
        SendEmailUtils.properties = properties;
    }

    public static MyAuthenticator getAuthenticator() {
        return authenticator;
    }

    public static void setAuthenticator(MyAuthenticator authenticator) {
        SendEmailUtils.authenticator = authenticator;
    }

    public SendEmailUtils() {
        properties = new Properties();
        properties.put("mail.smtp.host", "smtp.163.com");
        properties.put("mail.smtp.port", 25);
        properties.put("mail.smtp.auth", "true");
        authenticator = new MyAuthenticator("gyfavor@163.com","daqsoft");
    }

    public static void main(String[] args){
        new SendEmailUtils().sendMail(DateUtils.getCurrentDate("yy-MM-dd")+"备份","365223296@qq.com", "备份成功",  new String[]{("E:\\workspace\\nj\\nj1.sql")});
    }

    public boolean sendMail(String subject, String toMail,String content, String... files) {
        boolean isFlag = false;
        try {
            String smtpFromMail = authenticator.getUsername();  //账号
            String pwd = authenticator.getPassword(); //密码
            int port = Integer.valueOf(properties.getProperty("mail.smtp.port","25")); //端口
            String host = properties.getProperty("mail.smtp.host","smtp.163.com"); //端口

            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props);
            session.setDebug(false);

            MimeMessage message = new MimeMessage(session);
            try {
                message.setFrom(new InternetAddress(smtpFromMail, "邮箱数据备份服务"));
                message.addRecipient(Message.RecipientType.TO,new InternetAddress(toMail));
                message.setSubject(subject);
                message.addHeader("charset", "UTF-8");

                /*添加正文内容*/
                Multipart multipart = new MimeMultipart();
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setText(content);

                contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
                multipart.addBodyPart(contentPart);

                /*添加附件*/
                for (String file : files) {
                    File usFile = new File(file);
                    MimeBodyPart fileBody = new MimeBodyPart();
                    DataSource source = new FileDataSource(file);
                    fileBody.setDataHandler(new DataHandler(source));
//                    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//                    fileBody.setFileName("=?GBK?B?"+enc.encode(usFile.getName().getBytes()) + "?=");
                    multipart.addBodyPart(fileBody);
                }

                message.setContent(multipart);
                message.setSentDate(new Date());
                message.saveChanges();
                Transport transport = session.getTransport("smtp");

                transport.connect(host, port, smtpFromMail, pwd);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
                isFlag = true;
                System.out.println("邮件已发送");
            } catch (Exception e) {
                isFlag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isFlag;
    }

    public  boolean sendMailHtml(String title,String toAdd, String theme,String content) throws MessagingException{
        Address toAddress = new InternetAddress(toAdd);
        Session session = Session.getDefaultInstance(properties, authenticator);
        Message message = new MimeMessage(session);
        Address fromAddress = new InternetAddress(authenticator.getUsername());
        String nick="";
        try {
            nick=javax.mail.internet.MimeUtility.encodeText(title);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        message.setFrom(new InternetAddress(nick+" <"+fromAddress+">"));
        message.setRecipient(Message.RecipientType.TO, toAddress);
        // 设置邮件消息的主题
        message.setSubject(theme);
        // 设置邮件消息发送的时间
        message.setSentDate(new Date());
        // 设置邮件消息的主要内容HTML

        // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(content,"text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        message.setContent(mainPart);
        Transport.send(message);
        System.out.println("邮件已发送");
        return true;
    }
}
